import {
  orgParamPageApi,
  addOrgParamApi,
  editOrgParamApi,
  delOrgParamApi
} from '@/api/system/org'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'

type props = {
  orgId: number
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  drawerShow: Ref<boolean>
  orgParamForm: Ref<{ [index: string]: any }>
  proTableInst: Ref<ProTableInst | null>
}

export const useOrgParamApi = ({
  orgId,
  handleType,
  handleTag,
  drawerShow,
  orgParamForm,
  proTableInst
}: props) => {
  const confirmLoading = ref(false)
  // 获取参数列表
  const fetchOrgParamPage = async (pageRequest, queryParams) => {
    try {
      const res = await orgParamPageApi({
        ...queryParams,
        pageRequest,
        orgId
      })

      if (res.code === '0000') {
        return {
          data: res.data?.content,
          total: res.data?.total
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 新增or修改参数
  const fetchAddOrEditOrgParam = async () => {
    try {
      confirmLoading.value = true
      const fetch =
        handleType.value === 'add' ? addOrgParamApi : editOrgParamApi
      const res = await fetch({
        ...orgParamForm.value,
        orgId
      })
      if (res.code === '0000') {
        window['$message'].success(handleTag.value + '成功')
        proTableInst.value?.reload()
        drawerShow.value = false
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  // 删除参数
  const fetchDelOrgParam = async (id) => {
    try {
      const res = await delOrgParamApi({ id })
      if (res.code === '0000') {
        window['$message'].success('删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    fetchOrgParamPage,
    fetchAddOrEditOrgParam,
    fetchDelOrgParam
  }
}
